// pages/admin/manage/setting/index.js
const cloudHelper = require('../../../../helper/cloud_helper.js');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        list: [{},
            {},
            {},
        ],
    },

    onLoad(options) {
        this.getSetting();
    },

    // 获取配置
    async getSetting() {
        const data = await cloudHelper.callCloudData("api/admin/get_setting");
        if (data) {
            this.setData({
                list: data
            })
        }

    },

    // 保存配置
    async saveSetting() {
        const data = {
            list: this.data.list
        };
        const res = await cloudHelper.callCloudData("api/admin/save_setting", data);
        if (res) {
            wx.showToast({
                title: '保存成功',
            });
        } else {
            wx.showToast({
                title: '保存失败',
                icon: "error"
            });
        }
    },

    // 上传图片
    async uploadImage(_id, filePath) {
        // 上传头像
        wx.showLoading({
            title: '上传中...'
        });
        let pic = await cloudHelper.transTempPicOne(filePath, 'source/', '', false);
        wx.hideLoading();
        if (!pic) {
            wx.showToast({
                title: '上传失败',
                icon: 'error'
            });
            return;
        }
        this.setMyData(_id, pic);
    },

    // 图片改变
    onChooseImage(e) {
        const item = e.currentTarget.dataset.item;
        let that = this;
        wx.chooseMedia({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourcetype: ['album', 'camera'],
            success: res => {
                var filePath = res.tempFiles[0].tempFilePath;
                that.uploadImage(item._id, filePath);
            },
        });
    },

    // 布尔值改变
    onChangeBoole(e) {
        const item = e.currentTarget.dataset.item;
        const value = e.detail.value;
        this.setMyData(item._id, value);
    },

    // 输入框改变
    onChangeInput(e) {
        const item = e.currentTarget.dataset.item;
        const value = e.detail.value;
        this.setMyData(item._id, value);
    },

    // 配置数据
    setMyData(_id, value){
        const list = this.data.list;
        list.forEach(row => {
            if (row._id == _id) {
                row.value = value
            }
        });
        this.setData({
            list
        });
    }
})